package com.guxingke.nioserver.dispathcher;

import com.guxingke.nioserver.core.HttpMethod;
import com.guxingke.nioserver.core.HttpRequest;
import com.guxingke.nioserver.core.HttpResponse;
import com.guxingke.nioserver.exception.HttpException;
import com.guxingke.nioserver.handler.RestHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by guxingke on 15-8-19.
 */
public class RestDispatcher extends AbstartDispather {
    private Map<String, Class<? extends RestHandler>> mappings = new HashMap<String, Class<? extends RestHandler>>();

    public void addMapping(String resourceName, Class<? extends RestHandler> handler) {
        mappings.put(resourceName, handler);
    }

    @Override
    protected void dispatcher(HttpRequest request, HttpResponse response) throws HttpException {
        // 1.根据预先配置的mapping和requestUrl，匹配到对应的handler
        Class<? extends RestHandler> handlerClass = getHandler(request
                .getRequestUrl());
        if (handlerClass == null) {
            throw new HttpException(404);
        }

        RestHandler handler = null;
        try {
            handler = getHandler(handlerClass);
        } catch (InstantiationException | IllegalAccessException e) {
            throw new HttpException(500);
        }

        handler.init(request, response);
        // 2.调用handler中对应的方法
        HttpMethod method = request.getMethod();
        String id = request.getUrlPara();
        switch (method) {
            case GET:
                if (null != id) {
                    handler.get(id);
                } else {
                    handler.get();
                }
                break;
            case POST:
                handler.post();
                break;
            case PUT:
                handler.put();
                break;
            case DELETE:
                handler.delete(id);
                break;
        }
    }

    private RestHandler getHandler(Class<? extends RestHandler> handlerClass)
            throws InstantiationException, IllegalAccessException {
        return handlerClass.newInstance();
    }

    private Class<? extends RestHandler> getHandler(String requestUrl) {
        String resourceName = getResoureName(requestUrl);
        return mappings.get(resourceName);
    }

    private String getResoureName(String requestUrl) {
        int start = requestUrl.indexOf("/");
        int end = requestUrl.lastIndexOf("/");
        if (end == 0) {
            return requestUrl.substring(start + 1);
        }
        return requestUrl.substring(start + 1, end);
    }
}
